package com.shanghaionstar.user;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.exception.OnStarException;

import com.onstar.cn.common.util.MyPost;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.framework.mvp.base.core.BaseFragmentActivity;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.weight.DeleteEditText;
import com.onstar.cn.weight.ProgressLayout;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.MoreActivity;
import com.shanghaionstar.user.adapter.FeedBackAdapter;
import com.shanghaionstar.user.adapter.ViewHolder;
import com.shanghaionstar.user.iview.IFeedBackView;
import com.shanghaionstar.user.presenter.FeedBackPresenter;
import com.shanghaionstar.user.service.FeedBackService;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.weight.CommonProgressButton;
import com.shanghaionstar.weight.TopLayout;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 7828wc on 16/7/12.
 */
public class FeedBackFragment extends BaseFragment implements IFeedBackView,View.OnClickListener {
    @FindViewById
    private TopLayout            top_layout;
    @FindViewById
    private LinearLayout         datas_layout;
    @FindViewById
    private DeleteEditText       feedback_content;
    @FindViewById
    private TextView             edit_error_text;
    @FindViewById
    private GridView             picture_grid;
    @FindViewById
    private CommonProgressButton btn_submit;
    @FindViewById
    private RelativeLayout       success_layout;
    @FindViewById
    private ProgressLayout       progress_layout;

    private List<FeedBackService.ImgItem> imgList = new ArrayList<>();
    private BaseFragmentActivity mActivity;
    private static final int MAX_IMG = 4;
    private MoreActivity      parentActivity;
    private FeedBackAdapter   mAdapter;
    private FeedBackPresenter presenter;

    @Override
    public int getLayoutId() {
        return R.layout.more_feedback;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        parentActivity = (MoreActivity) getActivity();
        btnBackClick(top_layout);
        if (isFirstLoad()) {
            Drawable drawable = getResources().getDrawable(R.drawable.ic_fb_add);
            Bitmap bitmap = drawableToBitmap(drawable);
            FeedBackService.ImgItem item = new FeedBackService.ImgItem();
            item.bitmap = bitmap;
            imgList.add(item);
            presenter = new FeedBackPresenter(parentActivity.getScheduler(), parentActivity, imgList, feedback_content);
            presenter.setView(this);
        }
        mAdapter = new FeedBackAdapter(getActivity(), imgList, R.layout.user_feedback_item) {

            @Override
            public void convert(ViewHolder holder, FeedBackService.ImgItem item, int pos) {
                holder.setImageBitmap(R.id.fb_iv, item.bitmap);
                final int N = imgList.size();
                final int _position = pos;
                if (pos == N - 1) {
                    holder.setVisible(R.id.del_iv, false);
                    if (N > MAX_IMG)
                        holder.setImageResource(R.id.fb_iv, R.drawable.transparent_bg);
                    holder.setOnClickListener(R.id.fb_iv, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (N > MAX_IMG) {
                                return;
                            }
                            //showActionSheet();
                            presenter.showActionSheet();
                        }
                    });
                } else {
                    holder.setOnClickListener(R.id.fb_iv, null);
                    holder.setVisible(R.id.del_iv, true);
                }
                holder.setOnClickListener(R.id.del_iv, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (_position != N - 1) {
                            imgList.remove(_position);
                            notifyDataSetChanged();
                        }
                    }
                });
            }
        };

        picture_grid.setAdapter(mAdapter);
        feedback_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                edit_error_text.setVisibility(View.GONE);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private Bitmap drawableToBitmap(Drawable drawable) {
        BitmapDrawable bd = (BitmapDrawable) drawable;
        return bd.getBitmap();
    }


    private void showProgress() {
        progress_layout.setVisibility(View.VISIBLE);
    }

    private void dismissProgress() {
        progress_layout.setVisibility(View.GONE);
    }

    private String getExtension(String filePath) {
        String extension = ".png";
        try {
            if (filePath != null) {
                extension = filePath.substring(filePath.lastIndexOf("."));
            }
        } catch (Exception e) {
            e.printStackTrace();
            extension = ".png";
        }
        return extension;
    }

    public void processSelectedPhoto(String path) {
        FeedBackService.ImgItem item = new FeedBackService.ImgItem();
        item.bitmap = FeedBackBitmapUtil.createImageThumbnail(path);
        item.extension = getExtension(path);
        if (!imgList.isEmpty()) {
            imgList.add(imgList.size() - 1, item);
            MyPost.post(new Runnable() {
                @Override
                public void run() {
                    if (mAdapter != null)
                        mAdapter.notifyDataSetChanged();
                }
            });

        }

    }


    @Override
    public void setLoading(boolean isLoading) {
        progress_layout.setVisibility(isLoading ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onResponseError(OnStarException e) {
        dismissProgress();
        AlertDialogUtil.showDialogByExceptionCode(getActivity(), (HttpException) e);
    }

    @Override
    public void onReponseSuccess(FeedBackResult object) {
        dismissProgress();
        String json = GsonHelper.toJson(object);
        try {
            if (json.contains("E0000")) {
                success_layout.setVisibility(View.VISIBLE);
                datas_layout.setVisibility(View.GONE);
            } else {
                ToastView toastView = new ToastView(getActivity());
                JSONObject obj = new JSONObject(json);
                String description = obj.getString("description");
                toastView.showToast(description);
            }
        } catch (Exception e) {
            AlertDialogUtil.showDialogByExceptionCode(getActivity(), new HttpException());
          //  e.printStackTrace();
        }
    }

    @Override
    public Activity onActivity() {
        return getActivity();
    }

    @OnClick({R.id.btn_submit})
    @Override
    public void onClick(View v) {
                String text = feedback_content.getText().toString();
                if (TextUtils.isEmpty(text)) {
                    edit_error_text.setVisibility(View.VISIBLE);
                    edit_error_text.setText(R.string.feedback_hint);
                    return;
                }
                showProgress();
                //      uploadFeedbackImgs();
                presenter.start();

    }

}
